import React, { ReactNode, useEffect, useState } from 'react';
import type { NavigateFunction } from 'react-router-dom';
import { useNavigate } from 'react-router-dom';
import {
  Card,
  Row,
  Col,
  Button,
  Checkbox,
  DatePicker,
  Dropdown,
  Image,
  Space,
  Spin,
  Statistic,
  Typography,
  Modal,
  message
} from 'antd';
import { LinkOutlined, MoreOutlined } from '@ant-design/icons';
import type { MenuProps } from 'antd';
import dayjs from 'dayjs';
import Chart from '../components/Chart';
import dingTalkImageData from '../data/dingTalkImageData';
import feishuImageData from '../data/feishuImageData';
import neteaseImageData from '../data/neteaseImageData';
import wechatImageData from '../data/wechatImageData';
import { useStore, observer } from '../store/statistic/storeHook';
import { useStore as useUserStore } from '../store/user/storeHook';
import { useStore as useCompanyStore } from '../store/company/storeHook';
import { useStore as useTaskStore } from '../store/task/storeHook';
import { getDateText } from '../utils/dateUtil';
import { appTypes, getOptionLabel } from '../data/statusData';

const { RangePicker } = DatePicker;
const { Text, Title, Link, Paragraph } = Typography;

const Dashboard: React.FC = () => {
  const navigate: NavigateFunction = useNavigate();
  const [messageApi, contextHolder] = message.useMessage();

  const [isDateRangeModalOpen, setIsDateRangeModalOpen] = useState<boolean>(false);
  const [isNotesModalOpen, setIsNotesModalOpen] = useState<boolean>(false);
  const [isActiveUserCount, setIsActiveUserCount] = useState<boolean>(true);
  const [isActiveCompanyCount, setIsActiveCompanyCount] = useState<boolean>(true);
  const [isActiveTaskCount, setIsActiveTaskCount] = useState<boolean>(true);
  const [dateRange, setDateRange] = useState<[start: dayjs.Dayjs | null | undefined, end: dayjs.Dayjs | null | undefined]>([null, null]);
  const [currentAppType, setCurrentAppType] = useState<string>('Netease');

  const store: any = useStore();
  const userStore: any = useUserStore();
  const companyStore: any = useCompanyStore();
  const taskStore: any = useTaskStore();

  const menuItems: MenuProps['items'] = [
    {
      label: '昨天',
      key: 'yesterday'
    },
    {
      label: '最近7天',
      key: 'last7Days'
    },
    {
      label: '上一周',
      key: 'lastWeek'
    },
    {
      label: '上个月',
      key: 'lastMonth'
    },
    {
      label: '自定义日期范围',
      key: 'customDateRange'
    }
  ];

  const taskCountMenu: MenuProps = {
    items: menuItems,
    selectable: true,
    selectedKeys: [store.statistic.selectedKey],
    onClick: e => showTaskCountChart(e.key)
  };

  const getTaskCountLabel = (menuItems: MenuProps['items']) => {
    let label: ReactNode = '';
    (menuItems || []).forEach((item: any) => {
      if (item.key === store.statistic.selectedKey) {
        label = item.label;
      }
    });
    if (store.statistic.selectedKey === 'customDateRange') {
      label = `${store.statistic.startDate} 至 ${store.statistic.endDate}`;
    }
    return label;
  };

  const saveDateRange = () => {
    if (!dateRange[0] || !dateRange[1]) {
      messageApi.error('请选择日期范围');
      return;
    }
    store.statistic.setDates(getDateText(dateRange[0]), getDateText(dateRange[1]));
    setIsDateRangeModalOpen(false);
  };
  
  const showTaskCountChart = (key: string) => {
    if (key === 'customDateRange') {
      setDateRange([null, null]);
      setIsDateRangeModalOpen(true);
      return;
    }

    store.statistic.setSelectedKey(key ? key : 'customDateRange');
    const yesterday: string = dayjs().subtract(1, 'day').format('YYYY-MM-DD');
    if (key === 'yesterday') {
      store.statistic.setDates(yesterday, yesterday);
    } else if (key === 'last7Days') {
      store.statistic.setDates(dayjs().subtract(7, 'day').format('YYYY-MM-DD'), yesterday);
    } else if (key === 'lastWeek') {
      store.statistic.setDates(dayjs().subtract(1, 'week').day(1).format('YYYY-MM-DD'), dayjs().subtract(1, 'week').day(7).format('YYYY-MM-DD'));
    } else if (key === 'lastMonth') {
      store.statistic.setDates(dayjs().subtract(1, 'month').startOf('month').format('YYYY-MM-DD'), dayjs().subtract(1, 'month').endOf('month').format('YYYY-MM-DD'));
    }
    store.statistic.fetchTaskCounts();
  };

  const openNotesModal = (appType: string) => {
    setCurrentAppType(appType);
    setIsNotesModalOpen(true);
  };

  const openUserPage = () => {
    const conditions: any =  {
      keyword: '',
      active: isActiveUserCount ? 'true' : '',
      locked: '',
      superuser: '',
      type: '',
      pageNumber: 0
    };
    userStore.user.setConditions(conditions);
    navigate('/user_management');
  };

  const openCompanyPage = () => {
    const conditions: any =  {
      keyword: '',
      city: null,
      active: isActiveCompanyCount ? 'true' : '',
      owner: '',
      pageNumber: 0
    };
    companyStore.company.setConditions(conditions);
    navigate('/company_list');
  };

  const openTaskPage = () => {
    const conditions: any =  {
      keyword: '',
      company: [],
      appType: '',
      active: isActiveTaskCount ? 'true' : '',
      frequency: '',
      lastExecuteStatus: '',
      pageNumber: 0
    };
    taskStore.task.setConditions(conditions);
    navigate('/task_list');
  }

  useEffect(() => {
    store.statistic.fetchData();
  }, []); // eslint-disable-line react-hooks/exhaustive-deps

  return (
    <>
      {contextHolder}
      <Spin
        size="large"
        spinning={store.statistic.loading}
      >
        <Space
          direction="vertical"
          size={16}
          style={{
            padding: 16,
            width: '100%'
          }}
        >
          <Row
            gutter={16}
            className="data-statistics"
          >
            <Col xs={12} sm={12} md={12} lg={6} xl={6}>
              <Card variant="borderless">
                <Statistic
                  title={
                    <Space>
                      <Text
                        type="secondary"
                        className="link"
                        onClick={() => openUserPage()}
                      >
                        {`${isActiveUserCount ? '可用' : ''}用户`}
                      </Text>
                      <Checkbox
                        checked={isActiveUserCount}
                        onChange={e => setIsActiveUserCount(e.target.checked)}
                      />
                    </Space>
                  }
                  value={(isActiveUserCount ? store.statistic.counts?.activeUserCount : store.statistic.counts?.userCount) || 0}
                />
              </Card>
            </Col>
            <Col xs={12} sm={12} md={12} lg={6} xl={6}>
              <Card variant="borderless">
                <Statistic
                  title={
                    <Space>
                      <Text
                        type="secondary"
                        className="link"
                        onClick={() => openCompanyPage()}
                      >
                        {`${isActiveCompanyCount ? '可用' : ''}公司`}
                      </Text>
                      <Checkbox
                        checked={isActiveCompanyCount}
                        onChange={e => setIsActiveCompanyCount(e.target.checked)}
                      />
                    </Space>
                  }
                  value={(isActiveCompanyCount ? store.statistic.counts?.activeCompanyCount : store.statistic.counts?.companyCount) || 0}
                />
              </Card>
            </Col>
            <Col xs={12} sm={12} md={12} lg={6} xl={6}>
              <Card variant="borderless">
                <Statistic
                  title={<Text type="secondary">同步凭证</Text>}
                  value={store.statistic.counts?.certificateCount || 0}
                />
              </Card>
            </Col>
            <Col xs={12} sm={12} md={12} lg={6} xl={6}>
              <Card variant="borderless">
                <Statistic
                  title={
                    <Space>
                      <Text
                        type="secondary"
                        className="link"
                        onClick={() => openTaskPage()}
                      >
                        {`${isActiveTaskCount ? '可用' : ''}任务`}
                      </Text>
                      <Checkbox
                        checked={isActiveTaskCount}
                        onChange={e => setIsActiveTaskCount(e.target.checked)}
                      />
                    </Space>
                  }
                  value={(isActiveTaskCount ? store.statistic.counts?.activeTaskCount : store.statistic.counts?.taskCount) || 0}
                />
              </Card>
            </Col>
          </Row>
          <Card
            title={
              <span>
                任务统计
                <small style={{ marginLeft: 8 }}>
                  {getTaskCountLabel(menuItems)}
                </small>
              </span>
            }
            extra={
              <Dropdown
                menu={taskCountMenu}
                trigger={['click']}
              >
                <Button
                  type="link"
                  size="small"
                  icon={<MoreOutlined />}
                  iconPosition="end"
                  style={{
                    gap: 2,
                    height: 'auto',
                    padding: 0
                  }}
                >
                  选择统计项目
                </Button>
              </Dropdown>
            }
          >
            <Spin spinning={store.statistic.taskCountsLoading}>
              <Chart
                option={store.statistic.taskChartOption}
                width="100%"
                height={480}
              />
            </Spin>
          </Card>
          <Row
            gutter={16}
            style={{ marginBottom: -16 }}
          >
            <Col xs={24} sm={24} md={24} lg={24} xl={12}>
              <Card
                title="通讯与协作工具"
                style={{ marginBottom: 16 }}
              >
                <Space
                  direction="horizontal"
                  align="start"
                  size={24}
                  style={{
                    width: '100%',
                    height: 240,
                    overflowY: 'auto'
                  }}
                >
                  <Space
                    direction="vertical"
                    className="nowrap-links"
                  >
                    <Title level={5}>管理后台</Title>
                    <Link href="https://mail.qiye.163.com" target="_blank">
                      <Image
                        alt="Netease"
                        src={neteaseImageData}
                        preview={false}
                        style={{
                          marginRight: 5,
                          width: 16,
                          height: 16
                        }}
                      />
                      网易企业邮箱
                    </Link>
                    <Link href="https://work.weixin.qq.com/wework_admin/loginpage_wx?from=myhome" target="_blank">
                      <Image
                        alt="Wechat"
                        src={wechatImageData}
                        preview={false}
                        style={{
                          marginRight: 5,
                          width: 16,
                          height: 16
                        }}
                      />
                      企业微信管理后台
                    </Link>
                    <Link href="https://oa.dingtalk.com" target="_blank">
                      <Image
                        alt="DingTalk"
                        src={dingTalkImageData}
                        preview={false}
                        style={{
                          marginRight: 5,
                          width: 16,
                          height: 16
                        }}
                      />
                      钉钉管理后台
                    </Link>
                    <Link href="https://admin.feishu.cn" target="_blank">
                      <Image
                        alt="Feishu"
                        src={feishuImageData}
                        preview={false}
                        style={{
                          marginRight: 5,
                          width: 16,
                          height: 16
                        }}
                      />
                      飞书管理后台
                    </Link>
                  </Space>
                  <Space direction="vertical">
                    <Title level={5}>相关文档</Title>
                    <Link href="/netease_document.pdf" target="_blank">
                      <LinkOutlined style={{ marginRight: 5}} />
                      网易企业邮箱对外开放平台技术白皮书
                    </Link>
                    <Link href="https://developer.work.weixin.qq.com/document/path/90193" target="_blank">
                      <LinkOutlined style={{ marginRight: 5}} />
                      企业微信开发者中心 - 通讯录管理概述
                    </Link>
                    <Link href="https://open.dingtalk.com/document/orgapp/contacts-overview" target="_blank">
                      <LinkOutlined style={{ marginRight: 5}} />
                      钉钉开放平台开发文档 - 通讯录管理概述
                    </Link>
                    <Link href="https://open.feishu.cn/document/server-docs/contact-v3/resources" target="_blank">
                      <LinkOutlined style={{ marginRight: 5}} />
                      飞书开放平台开发文档 - 通讯录概述
                    </Link>
                  </Space>
                </Space>
              </Card>
            </Col>
            <Col xs={24} sm={24} md={24} lg={24} xl={12}>
              <Card
                title="注意事项与配置"
                style={{ marginBottom: 16 }}
              >
                <Space
                  direction="vertical"
                  className="notes"
                  style={{
                    width: '100%',
                    height: 240,
                    overflow: 'hidden'
                  }}
                >
                  <Row gutter={16}>
                    <Col span={12}>
                      <Button
                        type="link"
                        onClick={() => openNotesModal('Netease')}
                      >
                        <Image
                          alt="Netease"
                          src={neteaseImageData}
                          preview={false}
                          style={{
                            width: 64,
                            height: 64
                          }}
                        />
                      </Button>
                    </Col>
                    <Col span={12}>
                      <Button
                        type="link"
                        onClick={() => openNotesModal('Wechat')}
                      >
                        <Image
                          alt="Wechat"
                          src={wechatImageData}
                          preview={false}
                          style={{
                            width: 64,
                            height: 64
                          }}
                        />
                      </Button>
                    </Col>
                  </Row>
                  <Row gutter={16}>
                    <Col span={12}>
                      <Button
                        type="link"
                        onClick={() => openNotesModal('DingTalk')}
                      >
                        <Image
                          alt="DingTalk"
                          src={dingTalkImageData}
                          preview={false}
                          style={{
                            width: 64,
                            height: 64
                          }}
                        />
                      </Button>
                    </Col>
                    <Col span={12}>
                      <Button
                        type="link"
                        onClick={() => openNotesModal('Feishu')}
                      >
                        <Image
                          alt="Feishu"
                          src={feishuImageData}
                          preview={false}
                          style={{
                            width: 64,
                            height: 64
                          }}
                        />
                      </Button>
                    </Col>
                  </Row>
                </Space>
              </Card>
            </Col>
          </Row>

          <Modal
            title="选择日期范围"
            open={isDateRangeModalOpen}
            maskClosable={false}
            destroyOnHidden
            forceRender
            width={360}
            style={{ minWidth: 320 }}
            onOk={() => saveDateRange()}
            onCancel={() => setIsDateRangeModalOpen(false)}
            afterClose={() => {
              if (dateRange[0] && dateRange[1]) {
                showTaskCountChart('');
              }
            }}
            footer={(_, { OkBtn, CancelBtn }) => (
              <><OkBtn /><CancelBtn /></>
            )}
          >
            <RangePicker
              allowEmpty={[true, true]}
              format="YYYY-MM-DD"
              showTime={false}
              placeholder={['开始日期', '结束日期']}
              value={dateRange}
              style={{ margin: '16px 0' }}
              onChange={dates => setDateRange(dates ? dates : [null, null])}
            />
          </Modal>

          <Modal
            title={`注意事项与配置 - ${getOptionLabel(appTypes, currentAppType)}`}
            open={isNotesModalOpen}
            maskClosable={true}
            destroyOnHidden
            forceRender
            footer={null}
            className="notes-modal"
            onCancel={() => setIsNotesModalOpen(false)}
          >
            <>
              {currentAppType === 'Netease' && (
                <>
                  <Title level={5}>开通集成接口</Title>
                  <Paragraph>1. 请使用网易企业邮箱管理员 admin 邮箱发送邮件至 kf@office.163.com 申请开通集成接口功能，申请邮件格式如下（请将 xxx.com 修改为真实的客户企业邮箱域名）：</Paragraph>
                  <Paragraph className="indent">发件人：admin@xxx.com</Paragraph>
                  <Paragraph className="indent">收件人：kf@office.163.com</Paragraph>
                  <Paragraph className="indent">邮件主题：申请开通 API</Paragraph>
                  <Paragraph className="indent">邮件正文：</Paragraph>
                  <Paragraph className="indent">您好，因需要集成本地 xx 系统实现 xx 功能，现申请开通集成接口。</Paragraph>
                  <Paragraph className="indent">我网易企业域名为：xxx.com</Paragraph>
                  <Paragraph>2. 发送完邮件后等待网易管方客服邮件回复，回复的邮箱中将告知“已开通管理后台接口配置界面”。</Paragraph>
                </>
              )}
              {currentAppType === 'Wechat' && (
                <>
                  <Title level={5}>配置指南</Title>
                  <Paragraph>1. 企业ID在【企业微信管理后台 - 我的企业 - 企业信息 - 企业ID】中查看</Paragraph>
                  <Paragraph>2. 在【企业微信管理后台 - 应用管理 - 应用管理 - 应用 - 自建】中创建应用并获得应用凭证密钥（Secret），“可见范围”应选择组织架构的根部门</Paragraph>
                  <Paragraph>3. 通讯录同步密钥在 【企业微信管理后台 - 安全与管理 - 管理工具 - 通讯录同步 - Secret】 中查看</Paragraph>
                  <Paragraph>4. 需要开启通讯录同步权限，在【企业微信管理后台 - 安全与管理 - 管理工具 - 通讯录同步 - 权限】中设置“开启手动编辑”，并设置可修改字段</Paragraph>
                  <Paragraph>5. 需要配置企业可信IP，在【企业微信管理后台 - 安全与管理 - 管理工具 - 通讯录同步 - 企业可信IP】及【企业微信管理后台 - 应用管理 - 应用管理 - 应用 - xx应用 - 企业可信IP】中进行配置，IP地址为本应用所在服务器IP，多个IP地址用半角分号分隔</Paragraph>
                </>
              )}
              {currentAppType === 'DingTalk' && (
                <>
                  <Title level={5}>配置指南</Title>
                  <Paragraph>
                    1. 在
                    <Link href="https://open-dev.dingtalk.com/fe/app" target="_blank">
                      钉钉开放平台 - 应用开发
                    </Link>
                    中选择“企业内部应用 - 钉钉应用”，创建应用，然后在应用的“基础信息 - 凭证与基础信息”中获取应用AppKey（Client ID）和应用AppSecret（Client Secret）
                  </Paragraph>
                  <Paragraph>2. 在钉钉开放平台首页可以看到企业ID（CorpId）</Paragraph>
                  <Paragraph>3. 在钉钉开放平台对应的应用页面中的“开发配置 - 权限管理”中选择权限范围为“全部员工”，并在“通讯录管理”中添加必要的权限</Paragraph>
                </>
              )}
              {currentAppType === 'Feishu' && (
                <>
                  <Title level={5}>配置指南</Title>
                  <Paragraph>首先在【飞书管理后台 - 工作台 - 应用管理】中点击“创建应用”，然后在应用页面中【基础信息 - 凭证与基础管理】中可以获得应用唯一标识（App ID）和应用秘钥（App Secret）</Paragraph>
                  <Paragraph>然后在对应应用页面进入【开发配置 - 权限管理】为应用添加必要的权限及可访问的数据范围（建议选择“全部成员”）</Paragraph>
                </>
              )}
            </>
          </Modal>
        </Space>
      </Spin>
    </>
  );
};

export default observer(Dashboard);
